package renderer2;

import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;

import org.lwjgl.opengl.GL11;

public class Tessellator {
	private static int nativeBufferSize = 0x200000;// float. int
	private static int trivertsInBuffer = (nativeBufferSize / 48) * 6;// in size 4 *8 * 3

	private static ByteBuffer byteBuffer = GLAllocator.createDirectByteBuffer(nativeBufferSize * 4);
	private static IntBuffer intBuffer = byteBuffer.asIntBuffer();
	private static FloatBuffer floatBuffer = byteBuffer.asFloatBuffer();
	private static ShortBuffer shortBuffer = byteBuffer.asShortBuffer();

	public static Tessellator instance = new Tessellator();
	public int drawMode;

	private int[] rawBuffer;
	private static int rawBufferSize = 0;
	private int addedVertices;
	private int rawBufferIndex;
	private int vertexCount;

	public double xOffset;
	public double yOffset;
	public double zOffset;

	public void startDrawingQuads() {
		this.startDrawing(7);
	}

	public void draw() {
		int offs = 0;
		intBuffer.flip(); 
		while (offs < vertexCount) {
			int vtc = Math.min(vertexCount - offs, nativeBufferSize / 12);// 32
			
            this.intBuffer.clear();
            this.intBuffer.put(this.rawBuffer, offs * 3, vtc * 3);


			GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
			this.intBuffer.position(0);
			GL11.glVertexPointer(4, 16, this.intBuffer);
			GL11.glDrawArrays(GL11.GL_QUADS, 0, 6);
			GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
			offs = offs + vtc;
		}
	}

	public void addVertex(double par1, double par3, double par5) {
		if (rawBufferSize == 0) {
			rawBufferSize = 0x10000;
			rawBuffer = new int[rawBufferSize];
		}
		
		++this.addedVertices;
		this.rawBuffer[this.rawBufferIndex + 0] = Float.floatToRawIntBits((float) (par1 + this.xOffset));
		this.rawBuffer[this.rawBufferIndex + 1] = Float.floatToRawIntBits((float) (par3 + this.yOffset));
		this.rawBuffer[this.rawBufferIndex + 2] = Float.floatToRawIntBits((float) (par5 + this.zOffset));
		++this.vertexCount;
		this.rawBufferIndex += 3;
	}

	public void startDrawing(int par1) {
		this.drawMode = par1;
		resetVertexAndBuffer();
	}

	/**
	 * Sets the translation for all vertices in the current draw call.
	 */
	public void setTranslation(double par1, double par3, double par5) {
		this.xOffset = par1;
		this.yOffset = par3;
		this.zOffset = par5;
	}

	private void resetVertexAndBuffer() {
		this.addedVertices = 0;
		this.rawBufferIndex = 0;
	}

}
